<template>
  <div class="text-container">
    <el-card class="question-container">
      <div class="details">
        <h2 class="mark_title">{{ textInfo.title }}</h2>
        <div class="infoHead">
          <span>题量: {{ textInfo.questionCount }}</span>
        </div>
      </div>
      <div v-for="(questions, type, index) in groupedQuestions" :key="type">
        <h4 class="question-type">{{ getNumber(index + 1) }}、 {{ type }}</h4>
        <div v-for="(item, questionIndex) in questions" :key="questionIndex" class="question-item" :id="`${type}-question${questionIndex + 1}`">
          <p>{{ questionIndex + 1 }}. {{ item.content }}</p>

          <!-- 处理多选题 -->
          <template v-if="type === '多选题'">
            <el-checkbox-group v-model="item.userAnswer">
              <el-checkbox v-for="(option, optionIndex) in item.options" :key="optionIndex" :label="`(${String.fromCharCode(65 + optionIndex)}) ${option}`">
                {{ String.fromCharCode(65 + optionIndex) }}. {{ option }}
              </el-checkbox>
            </el-checkbox-group>
            <!-- 显示学生答案 -->
            <div v-if="item.displayAnswer" style="color: green; margin-top: 10px;">
              <p>学生答案：{{ formatUserAnswer(item.userAnswer) }}</p>
              <p>正确答案：{{ formatAnswer(item.answer) }}</p>
            </div>
          </template>

          <!-- 处理单选题 -->
          <template v-else-if="type === '单选题'">
            <el-radio-group v-model="item.userAnswer">
              <el-radio v-for="(option, optionIndex) in item.options" :key="optionIndex" :label="`(${String.fromCharCode(65 + optionIndex)}) ${option}`">
                {{ String.fromCharCode(65 + optionIndex) }}. {{ option }}
              </el-radio>
            </el-radio-group>
            <!-- 显示学生答案 -->
            <div v-if="item.displayAnswer" style="color: green; margin-top: 10px;">
              <p>学生答案：{{ formatUserAnswer(item.userAnswer) }}</p>
              <p>正确答案：{{ formatAnswer(item.answer) }}</p>
            </div>
          </template>

          <!-- 处理填空题 -->
          <template v-else-if="type === '填空题'">
            <el-input v-model="item.userAnswer" placeholder="请输入答案" class="fill-input" />
            <!-- 显示学生答案 -->
            <div v-if="item.displayAnswer" style="color: green; margin-top: 10px;">
              <p>学生答案：{{ item.userAnswer }}</p>
              <p>正确答案：{{ formatAnswer(item.answer) }}</p>
            </div>
          </template>

          <!-- 处理简答题 -->
          <template v-else-if="type === '简答题'">
            <el-input type="textarea" :autosize="{minRows: 3}" v-model="item.userAnswer" placeholder="请输入您的回答" class="essay-input" />
            <!-- 显示学生答案 -->
            <div v-if="item.displayAnswer" style="color: green; margin-top: 10px;">
              <p>学生答案：{{ item.userAnswer }}</p>
              <p>正确答案：{{ formatAnswer(item.answer) }}</p>
            </div>
          </template>

          <!-- 处理判断题 -->
          <template v-else-if="type === '判断题'">
            <el-radio-group v-model="item.userAnswer">
              <el-radio label="正确">正确</el-radio>
              <el-radio label="错误">错误</el-radio>
            </el-radio-group>
            <!-- 显示学生答案 -->
            <div v-if="item.displayAnswer" style="color: green; margin-top: 10px;">
              <p>学生答案：{{ item.userAnswer }}</p>
              <p>正确答案：{{ formatAnswer(item.answer) }}</p>
            </div>
          </template>
        </div>
      </div>

      <el-button type="primary" @click="checkAnswers">提交答案</el-button>
    </el-card>

    <el-card class="index-container">
      <div v-for="(questions, type, index) in groupedQuestions" :key="type">
        <h5>{{ getNumber(index + 1) }}、{{ type }} ({{ questions.length }}题)</h5>
        <div class="numbers">
          <el-button v-for="(item, index) in questions" :key="index" type="primary" plain @click="scrollToQuestion(type, index + 1)">
            {{ index + 1 }}
          </el-button>

        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getTestQuestion } from "@/api/getTestQuestion";
import { MessageBox } from 'element-ui';  // 导入MessageBox
// import { submitAnswers } from "@/api/submitAnswer";

export default {
  name: 'testPage',
  data() {
    return {
      courseId:this.$route.params.courseId,
      chapterId:this.$route.params.chapterId,
      activeQuestion: 1, // 默认聚焦第一个问题
      questions: [],// 存储从后端获取的题目信息
      textInfo:{
        title: this.$route.query.title || '',  // 获取路由中的标题参数
        questionCount: 0,  // 题量
        totalScore: 100,   // 满分
      },
    };
  },
  methods: {
    async fetchTestQuestions() {
      try {
        // console.log(this.courseId)
        // const chapterId = this.$route.params.chapterId;  // 从路由参数中获取章节ID
        const response = await getTestQuestion(this.courseId, this.chapterId);
        console.log(response);
        this.textInfo.questionCount = response.length;
        // totalScore: 100,   计算满分的逻辑
        this.questions = response.map(q => {
          return {
            question_type: q.question_type,
            content: q.content,
            options: JSON.parse(q.option),  // 将JSON字符串解析为对象
            userAnswer: q.question_type === '多选题' ? [] : null,  // 多选题的答案初始化为空数组
            answer: q.answer,
          };
        });

      } catch (error) {
        console.error('获取题目失败:', error);
      }
    },
    checkAnswers() {
      // 检查是否有未作答的题目
      const unansweredQuestions = this.questions.filter(q => {
        if (q.question_type === '单选题' || q.question_type === '多选题' || q.question_type === '判断题') {
          return q.userAnswer === null || q.userAnswer.length === 0;
        } else if (q.question_type === '填空题') {
          return !q.userAnswer;
        } else if (q.question_type === '简答题') {
          return !q.userAnswer || q.userAnswer.trim() === '';
        }
        return false;
      });

      // 如果有未作答的题目，弹出提示框
      if (unansweredQuestions.length > 0) {
        MessageBox.confirm(
            '你还有未作答的题目，是否继续提交？',
            '提示',
            {
              confirmButtonText: '是',
              cancelButtonText: '否',
              type: 'warning'
            }
        ).then(() => {
          // 用户点击"是"时，继续执行提交逻辑
          this.submitAnswers();
        }).catch(() => {
          // 用户点击"否"时，取消提交
          console.log('用户取消提交');
        });
      } else {
        // 如果没有未作答的题目，直接提交
        this.submitAnswers();
      }
    },
    submitAnswers() {
      let correct = 0;  // 记录正确的题目数量
      let objectiveCount = 0;  // 记录客观题的数量

      this.questions.forEach(q => {
        const isObjective = q.question_type === '单选题' || q.question_type === '多选题' || q.question_type === '判断题' || q.question_type === '填空题';

        if (isObjective) {
          objectiveCount++;
          const formattedUserAnswer = this.formatUserAnswer(q.userAnswer);
          const formattedCorrectAnswer = this.formatAnswer(q.answer);
          if (this.isAnswerCorrect(formattedUserAnswer, formattedCorrectAnswer)) {
            correct++;
          }
        }
        this.$set(q, 'displayAnswer', true); // 显示答案
      });

      const accuracyRate = objectiveCount > 0 ? (correct / objectiveCount) * 100 : 0;
      this.$message({
        message: `你正确回答了 ${correct} / ${objectiveCount} 题，正确率为 ${accuracyRate.toFixed(2)}%`,
        type: 'success',
        duration: 5000
      });
    },

    // 用于比较学生答案和正确答案的正确性
    isAnswerCorrect(userAnswer, correctAnswer) {
      if (Array.isArray(userAnswer) && Array.isArray(correctAnswer)) {
        // 对于多选题，排序后进行比较
        userAnswer = userAnswer.sort();
        correctAnswer = correctAnswer.sort();
        return JSON.stringify(userAnswer) === JSON.stringify(correctAnswer);
      } else if (!Array.isArray(userAnswer) && !Array.isArray(correctAnswer)) {
        // 对于单选题和判断题，直接比较字符串
        return userAnswer === correctAnswer;
      }
      return false; // 处理不匹配的情况
    },
    // 格式化学生答案，提取括号中的选项字母
    formatUserAnswer(userAnswer) {
      if (Array.isArray(userAnswer)) {
        // 如果是多选题，userAnswer是一个数组，提取每个选项的字母部分
        return userAnswer.map(answer => {
          const match = answer.match(/\(([^)]+)\)/);  // 提取括号中的字母
          return match ? match[1] : ''; // 返回字母部分
        }).join(', '); // 连接字母，用逗号分隔
      }else if (typeof userAnswer === 'string') {
        // 如果是字符串类型，处理包含字母和答案内容的情况
        const matches = userAnswer.match(/\(([A-Z])\)/g); // 匹配格式 (A), (B), (C) 等
        if (matches) {
          // 提取括号中的字母，并返回以逗号分隔的字母字符串
          return matches.map(match => match[1]).join(', ');
        } else return userAnswer;
      }
      return ''; // 如果不是字符串或数组，返回空字符串
    },
    // 格式化答案，去掉数组中的[]和双引号
    formatAnswer(answer) {
      // 将JSON字符串解析为数组，然后返回数组的第一个元素或拼接成字符串
      const parsedAnswer = JSON.parse(answer);
      if (Array.isArray(parsedAnswer)) {
        return parsedAnswer.join(', '); // 如果是数组，拼接成逗号分隔的字符串
      }
      return parsedAnswer; // 如果已经是一个单独的值，直接返回
    },
    getNumber(index) {
      const numbers = ['一', '二', '三', '四', '五'];
      return numbers[index - 1] || index; // 超出范围时返回数字本身
    },
    // 滚动到指定的题目
    scrollToQuestion(type, questionIndex) {
      const questionId = `${type}-question${questionIndex}`; // 构建包含类型的题目ID
      const target = document.getElementById(questionId);
      if (target) {
        target.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
    },

  },
  computed: {
    groupedQuestions() {
      const groups = {
        '单选题': [],
        '多选题': [],
        '判断题': [],
        '填空题': [],
        '简答题': [],
      };

      this.questions.forEach(question => {
        if (groups[question.question_type]) {
          groups[question.question_type].push(question);
        } else {
          console.warn(`Unknown question type: ${question.question_type}`);
        }
      });

      return groups;
    },
  },
  created() {
    this.fetchTestQuestions();  // 组件创建时获取题目列表
  }
  /* async checkAnswers() {
     try {
       // 构造提交数据
       const answers = this.questions.map(q => ({
         questionId: q.question_id,
         userAnswer: q.userAnswer,
       }));
       // 向后端发送学生答案
       const response = await submitAnswers({ answers });
       // 处理后端返回的数据，正确题数、错误题数
       const { correctCount, totalCount, analysis } = response.data;
       console.log(response.data)
       // 显示正确题数，页面跳转到结果页面
       this.$router.push({
         path: '/testResult',
         query: {
           correctCount,
           totalCount,
           analysis: JSON.stringify(analysis),
         },
       });
     } catch (error) {
       console.error("提交答案失败:", error);
       this.$message.error("提交答案失败，请重试！");
     }
   },

   scrollToQuestion(index) {
     const element = document.getElementById('question' + index); // 获取对应题目的DOM元素
     if (element) {
       element.scrollIntoView({ behavior: 'smooth' }); // 平滑滚动到元素
     }
   },*/
};
</script>

<style scoped>
.fill-input {
  width: 200px; /* 填空题输入框宽度 */
  margin-top: 15px;
}

.essay-input {
  width: 100%; /* 简答题输入框宽度 */
  min-height: 80px; /* 设置简答题输入框的最小高度 */
  margin-top: 15px;
}

/* 多选题选项竖排样式 */
.el-checkbox-group {
  display: flex;
  flex-direction: column;
}
.el-checkbox{
  margin-top: 10px;
  color: #303133;
}
.question-type{
  margin-bottom: 10px;
}
.details {
  border-bottom: 1px solid #F2F2F2;
  padding-bottom: 20px;
  position: relative;
  height: 87px;
  margin-bottom: 20px;
}
.mark_title {
  line-height: 25px;
  padding: 10px 10px 0;
  font-size: 18px;
  color: #181E33;
  font-weight: bold;
  width: 575px;
}
.infoHead {
  float: left;
  padding: 10px 0 0 10px;
  overflow: hidden;
  line-height: 16px;
  color: #A8A8B3;
  font-size: 14px;
}
.infoHead span {
  display: inline-block;
  padding-right: 20px;
}
.response-time p{
  display: inline-block;
  border-left: 1px solid #f2f2f2;
  height: 16px;
  line-height: 16px;
  padding: 0 14px;
  margin-left: -6px;
}
.text-container {
  padding-left: 500px;
  padding-top: 30px;
  margin: 0;
  height: 100%;
  background-color: #F2F4F7;
}
.question-container {
  border-radius: 10px;
  width: 860px;
  min-height:100vh;
  margin-left: 15px;
}

.question-item {
  margin-bottom: 20px;
}
.question-item .el-radio {
  color: #303133;
  margin: 11px 0; /* 为选项之间添加一些空间 */
}
.el-radio-group {
  display: flex;
  flex-direction: column;
}
.index-container {
  position: fixed;
  left: 100px;
  top: 30px;
  border-radius: 10px;
  margin-left: 10px;
  padding-top: 0;
  width: 300px;
 /* height: 550px;*/
}

.numbers {
  display: flex;
  flex-wrap: wrap;
  justify-content: start;

}

.numbers .el-button {
  margin: 5px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

</style>
